package org.stayfool.auth.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;

/**
 * @author jych
 */
public final class JsonUtil {

    private static final ObjectMapper om = new ObjectMapper();

    static {
        om.registerModule(new Hibernate5Module());
    }

    private JsonUtil() {
        // singleton
    }

    /**
     * {@code Object} convert to json {@code String}
     *
     * @param obj
     * @return json string
     */
    public static final String toJson(Object obj) {
        if (obj == null)
            return null;

        try {
            return om.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * read {@code Object} from json {@code String}
     *
     * @param json
     * @param cls
     * @return {@code T} t
     */
    public static final <T> T fromJson(String json, Class<T> cls) {

        T t = null;

        if (StringUtil.isNullOrEmpty(json) || cls == null)
            return t;

        try {
            t = om.readValue(json, cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }
}
